#include "stdafx.h"
#include "ProgressLua.h"


namespace ProgressLua
{

	bool push(lua_State* L, Progress* pProgress)
	{
		Progress** pp = (Progress**)lua_newuserdata(L, sizeof(Progress*));
		*pp = pProgress;
		luaL_getmetatable(L, "woe.Progress");
		if (lua_istable(L, -1))
		{
			lua_setmetatable(L, -2);
			return true;
		}
		else
		{
			LOG_ERROR("Failed to push Progress to lua, metatable not found!");
			return false;
		}
	}

	Progress* getUserData(lua_State* L)
	{
		Progress**pp = (Progress**)luaL_checkudata(L, 1, "woe.Progress");
		if (pp==NULL)
		{
			return NULL;
		}
		else
		{
			return *pp;
		}
	}

	int set(lua_State* L)
	{
		Progress* pProgress = getUserData(L);
		if (pProgress)
		{
			char cid = (char)luaL_checkint(L, 2);
			char did = (char)luaL_checkint(L, 3);
			char sid = (char)luaL_checkint(L, 4);
			char val = (char)lua_tointeger(L, 5);

			ProgressDistrict* pd = pProgress->add(cid, did);
			pd->set(sid, val);
		}
		return 0;
	}

	int get(lua_State* L)
	{
		Progress* pProgress = getUserData(L);
		if (pProgress)
		{
			char cid = (char)luaL_checkint(L, 2);
			char did = (char)luaL_checkint(L, 3);
			char sid = (char)luaL_checkint(L, 4);
			char val = 0;
			ProgressDistrict* pd = pProgress->get(cid, did);
			if (pd && pd->get(sid, val))
			{
				lua_pushinteger(L, int(val));
			}
			else
			{
				lua_pushinteger(L, 0);
			}
			return 1;
		}
		return 0;
	}


	static const luaL_Reg Progress_funcs[] = {
		{"set", set},
		{"get", get},
		{NULL, NULL}
	};


	int libaray(lua_State* L)
	{
		luaL_newmetatable(L, "woe.Progress");
		// fill member list into metatable
		luaL_register(L, NULL, Progress_funcs);

		// metatable.__index = metatable
		lua_pushstring(L, "__index");
		lua_pushvalue(L, -2);
		lua_settable(L, -3);

		return 0;
	}

} // end of Progress lua
